package com.example.calendarprovider;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.net.wifi.aware.PublishConfig;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.calendarprovider.adapter.ImageAdapter;
import com.example.calendarprovider.bean.ImageItem;

import java.util.ArrayList;
import java.util.List;

public class PickerActivity extends AppCompatActivity implements ImageAdapter.OnItemSelectChangeListener {

    private static final String TAG = "PickerActivity";
    private static final int LOAD_ID = 1;

    private List<ImageItem> mImageItems = new ArrayList<>();
    private ImageAdapter mImageAdapter;
    private TextView mFinishView;
    private PickConfig mPickConfig;
    private int mSelectSize;
    private ImageView mPick_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picker);
//
//        ContentResolver contentResolver = getContentResolver();
//        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//        Cursor query = contentResolver.query(uri, null, null, null, null, null);
//        String[] columnNames = query.getColumnNames();
//        while (query.moveToNext()){
//            Log.d(TAG, "=============== ");
//            for(String columnName:columnNames){
//                Log.d(TAG, columnName+"===="+query.getString(query.getColumnIndex(columnName)));
//            }
//        }
//        query.close();
        loadImageManager();

        initView();
        initConfig();
        initEvent();


    }

    private void initConfig() {
        mPickConfig = PickConfig.getInstance();
        int maxSelectCount = mPickConfig.getMaxSelectCount();
        mImageAdapter.setMaxSelectCount(maxSelectCount);
        Log.d(TAG, " initTestConfig");
    }

    private void initEvent() {
        mSelectSize = getIntent().getIntExtra("selectSize",0);
        Log.d(TAG, "initEvent: "+ mSelectSize);
        //将选完后的数据给适配器
        mImageAdapter.setSelectSize(mSelectSize);
        mImageAdapter.setOnItemSelectChangeListener(this);
        //点击完成后
        mFinishView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<ImageItem> result = new ArrayList<>();
                Log.d(TAG, "initTestEvent: " + mPickConfig);
                //获取所选择的数据(因为之前已经设置（绑定适配器）所以可以相互通信)
                result.addAll(mImageAdapter.getSelectItem());
                mImageAdapter.realse();
                //通知其他地方
                PickConfig.OnImageSelectedFinishListener imageSelectedFinishListener = mPickConfig.getOnItemSelectFinishListener();
                if (imageSelectedFinishListener != null) {
                    imageSelectedFinishListener.onSelectFinished(result);
                }
                //结束界面
                finish();

            }
        });
        mPick_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initView() {
        mFinishView = findViewById(R.id.finish_tv);
        mPick_back = findViewById(R.id.pick_back);
        RecyclerView listView = findViewById(R.id.image_list_view);
        listView.setLayoutManager(new GridLayoutManager(this, 3));
        //设置适配器
        mImageAdapter = new ImageAdapter();
        listView.setAdapter(mImageAdapter);
    }

    //加载媒体库图片
    private void loadImageManager() {
        mImageItems.clear();
        //回调都在主线程
        LoaderManager loaderManager = LoaderManager.getInstance(this);
        loaderManager.initLoader(LOAD_ID, null, new LoaderManager.LoaderCallbacks<Cursor>() {

            //加载返回去给他
            @Override
            public Loader<Cursor> onCreateLoader(int id, @Nullable Bundle args) {
                if (id == LOAD_ID) {
                    return new CursorLoader(PickerActivity.this,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            //拿到三个字段的数据
                            new String[]{"_data", "_display_name", "date_added"}, null, null,
                            "date_added DESC");//逆序
                }
                return null;
            }

            //加载结束
            @Override
            public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor) {
                if (cursor != null) {
                    String[] columnNames = cursor.getColumnNames();
                    while (cursor.moveToNext()) {
//                     Log.d(TAG, "======================");
//                     for(String columnName:columnNames){
//                         Log.d(TAG, columnName+"===="+cursor.getString(cursor.getColumnIndex(columnName)));
//                     }
//                     Log.d(TAG, "======================= ");
                        String path = cursor.getString(0);
                        String title = cursor.getString(1);
                        long date = cursor.getLong(2);
                        ImageItem imageItem = new ImageItem(path, title, date);
                        mImageItems.add(imageItem);
                    }
                    cursor.close();
                    Log.d(TAG, " mImageItems " + mImageItems);
                    mImageAdapter.setData(mImageItems);

                }
            }

            //重置
            @Override
            public void onLoaderReset(@NonNull Loader<Cursor> loader) {

            }
        });
    }

    @Override
    public void onItemSelectChange(List<ImageItem> selectItems) {
        //所选择的数据发生变化
        //mFinishView.setText("" + selectItems.size() + "" + mImageAdapter.getMaxSelectCount());
        mFinishView.setText("（已选中" + selectItems.size() + "）完成");

    }

}